package com.study.controller.admin;

import com.study.constant.JwtClaimsConstant;
import com.study.dto.AdministratorDTO;
import com.study.entity.Admin;
import com.study.properties.JwtProperties;
import com.study.result.Result;
import com.study.service.AdminService;
import com.study.utils.JwtUtil;
import com.study.vo.AdminLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController("adminLoginController")
@RequestMapping("/admin")
@Slf4j
@Api(tags = "管理员接口")
public class AdminController {

    @Autowired
    AdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("员工登录")
    public Result<AdminLoginVO> login(String username, String password) {
        log.info("员工登录");

        Admin admin = adminService.login(username, password);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID, admin.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        AdminLoginVO adminLoginVO = AdminLoginVO.builder()
                .id(admin.getId())
                .userName(admin.getUsername())
                .name(admin.getName())
                .token(token)
                .build();

        return Result.success(adminLoginVO);
    }

    /**
     * 添加管理员账号
     * @param administratorDTO
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("添加管理员账号")
    public Result add(@RequestBody AdministratorDTO administratorDTO) {
        adminService.addAdministrator(administratorDTO);
        return Result.success();
    }
}
